package com.woniuxy.ssm.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义转换器
 */
@Component
public class StringToDateConverter implements Converter<String, Date> {
    /**
     * String 转向 Date
     * @param s  2021-09-27  |   2021-09-27 12:12:12
     * @return
     */
    @Override
    public Date convert(String s) {

        SimpleDateFormat sdf = null;
        try{
            if(!StringUtils.hasLength(s)){
                return null;
            }else{
                //匹配格式 yyyy-MM-dd (短)   yyyy-MM-dd hh:mm:ss
                Pattern pattern = Pattern.compile("^\\d{4}\\-(0[1-9]|1[012])\\-(0[1-9]|[12][0-9]|3[01])$");
                Matcher m = pattern.matcher(s);
                if(m.matches()){//短格式
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                }else{//长格式
                    sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                }
                Date parse = sdf.parse(s);
                return parse;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
